/**
 * 数据管理工具
 * 统一管理文物和主题数据
 */

import { Artifact, ArtifactBase } from '../types/artifact'
import { Theme, ThemeBase } from '../types/theme'
import { artifactsConfig } from '../config/artifacts'
import { themesConfig } from '../config/themes'

class DataManager {
  private artifacts: Map<string, ArtifactBase> = new Map()
  private themes: Map<string, ThemeBase> = new Map()

  constructor() {
    this.loadData()
  }

  // 加载配置数据
  private loadData() {
    // 加载文物数据
    artifactsConfig.forEach(artifact => {
      this.artifacts.set(artifact.id, new ArtifactBase(artifact))
    })

    // 加载主题数据
    themesConfig.forEach(theme => {
      this.themes.set(theme.id, new ThemeBase(theme))
    })
  }

  // 获取所有主题
  getAllThemes(): ThemeBase[] {
    return Array.from(this.themes.values()).sort((a, b) => a.order - b.order)
  }

  // 根据ID获取主题
  getThemeById(id: string): ThemeBase | undefined {
    return this.themes.get(id)
  }

  // 获取所有文物
  getAllArtifacts(): ArtifactBase[] {
    return Array.from(this.artifacts.values())
  }

  // 根据ID获取文物
  getArtifactById(id: string): ArtifactBase | undefined {
    return this.artifacts.get(id)
  }

  // 根据主题ID获取文物列表
  getArtifactsByThemeId(themeId: string): ArtifactBase[] {
    const theme = this.themes.get(themeId)
    if (!theme) return []
    
    return theme.artifactIds
      .map(id => this.artifacts.get(id))
      .filter((artifact): artifact is ArtifactBase => artifact !== undefined)
  }

  // 搜索文物（根据名称）
  searchArtifacts(keyword: string, locale: 'zh' | 'en' = 'zh'): ArtifactBase[] {
    const lowerKeyword = keyword.toLowerCase()
    return Array.from(this.artifacts.values()).filter(artifact => {
      const name = artifact.getName(locale).toLowerCase()
      const description = artifact.getDescription(locale).toLowerCase()
      return name.includes(lowerKeyword) || description.includes(lowerKeyword)
    })
  }
}

// 导出单例
export const dataManager = new DataManager()

